package com.zhkj.txg.module.mine.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.module.mine.entity.DeleteArticleResponse
import com.zhkj.txg.module.mine.entity.PublishListResponse
import com.zhkj.txg.module.mine.model.MineManager

class ArticleViewModel(application: Application) : BaseViewModel(application) {
    private val manager = MineManager()
    val articleListLiveData = MutableLiveData<HttpResponse<PublishListResponse>>()
    val deleteArticleLiveData = MutableLiveData<HttpResponse<DeleteArticleResponse>>()

    private val numb = 20
    var page = 1
        private set

    fun getPublishArticle(restart: Boolean) {
        val listener =
            object : ViewModelSubscribeListener<PublishListResponse>(articleListLiveData) {
                override fun onSuccess(resp: PublishListResponse) {
                    resp.hasMore = resp.data.size >= numb
                    resp.loadMore = page > 1
                    super.onSuccess(resp)
                    page += 1
                }
            }
        if (restart) page = 1
        val articleList =
            manager.publishArticleList(AccountManager.getToken(), page, numb, listener)
        dispose.add(articleList)
    }

    fun deleteArticle(id: Long, uiPosition: Int) {
        val listener = object : ViewModelSubscribeListener<DeleteArticleResponse>(deleteArticleLiveData) {
            override fun onSuccess(resp: DeleteArticleResponse) {
                resp.uiPosition = uiPosition
                super.onSuccess(resp)
            }
        }
        val deleteArticle = manager.deletePublishArticle(AccountManager.getToken(), id, listener)
        dispose.add(deleteArticle)
    }
}